package be.technofutur.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LottoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		doPost (request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		LottoInit lotto = new LottoInit();
		int[] lottoArray = new int[6];
		List<Integer> choosedNumberArray = new ArrayList<Integer>();
		lottoArray = lotto.toIntArray(lotto.randomizeSelections());
        out.println("<!DOCTYPE html><html><head><title>Lotto Servlet !</title></head>");
        out.println("<body><h1 align=center>LOTTO</h1>");
        out.print("<p align=center>chiffre Gagnant : [");
        int c = 0;
        for (int i : lottoArray) 
        {
        	if (c <lottoArray.length-1 ) 
        	{
        		out.print(" "+i+", ");
        		c++;
			} else 
			{
				out.print(" "+i);
				c++;
			}
		}
        out.println (" ]</p> <center><form method=\"POST\" action=\"/HelloWeb/Lotto\"><TABLE><TR>");
        for (int i = 0; i < 42; i++) 
        {
        	if (i%7 == 0)
        	{
        		out.println("</TR><TR>");
        	}
        	out.print("<TD><input type=\"checkbox\" name=\"number\" value=\""+(i+1)+"\"/>"+(i+1)+"</TD>");
		}
   		out.println("</TR></TABLE><INPUT type=\"submit\" value=\"PLAY\"/ ></form> ");
   		out.print("<br>");
   		String [] choosedNumber = null;
   		choosedNumber = request.getParameterValues("number");
   			for (String s : choosedNumber)
   			{
   			choosedNumberArray.add(Integer.valueOf(s));
   			}
   		
   		out.print(choosedNumberArray);
   		
   		int cpt = 0;
   		
   		for (int i : lottoArray) 
        {
        	for (Integer num : choosedNumberArray) {
				if (i == num) 
				{
					cpt++;
				}
			}
		}
   		if (cpt == 6) 
   		{
   			out.print("<br>VOUS AVEZ GAGNE");
		} else 
		{
			out.print("<br>Vous avez : "+cpt+" nombre correct<br>VOUS AVEZ PERDU");
		}
   		
   		out.println("</center></body></html>");
       
        
	}

}
